package com.snpic.appaw.module.insure.util.s3;


import com.amazonaws.services.s3.AmazonS3;
import com.snpic.appaw.module.insure.config.S3Config;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件处理工具类
 */
@Component
public class FileUtil {
	private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
	@Resource
	private S3Config s3Config;

	/**
	 * @param file   文件对象
	 * @param BizDir 业务文件夹,vehicle_license/
	 * @return
	 */
	@NotNull
	public String getUniqueFilename(MultipartFile file, String BizDir) {
		// 生成唯一的文件名
		String originalFilename = file.getOriginalFilename();
		String fileExtension = StringUtils.getFilenameExtension(originalFilename);
		LocalDateTime now = LocalDateTime.now();
		String timestamp = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
		String datePath = now.format(DateTimeFormatter.ofPattern("yyyy-MM"));
		String uniqueFilename = s3Config.getBasePath() + BizDir + datePath + "/" + timestamp + "_" + UUID.randomUUID() + "." + fileExtension;
		return uniqueFilename;
	}


	public static void main(String[] args) throws IOException {
		InputStream inputStream = new FileUtil().getInputStream("https://records.icsoc.net/saas_ali/call/88/20211124/2001799/43/20211124083349-6869070478628118528-132526507-0-6020065-16523163428-342.mp3");
		log.info("inStream.toString():" + inputStream.toString());
	}

	/**
	 * 通过url下载文件转换成io流
	 *
	 * @param url
	 * @return
	 */
	public InputStream getInputStream(String url) throws IOException {
		InputStream inStream = null;
		HttpURLConnection conn = null;
		try {
			log.info("URL:" + url);
			URL httpUrl = new URL(url);
			conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			inStream = conn.getInputStream();//通过输入流获取图片数据
			log.info("inStream.toString():" + inStream.toString());
//            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
		} catch (Exception e) {
			log.error("getFileByte is error:", e);
		} finally {
			if (inStream != null)
				inStream.close();
			if (conn != null)
				conn.disconnect();
		}
		return inStream;
	}

	/**
	 * InputStream 转 byte
	 *
	 * @param input
	 * @return
	 * @throws IOException
	 */
	public byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}


	/**
	 * 功能：截取出第一个标志位之后的字符串.<br/>
	 * 如果sourceStr为empty或者expr为null，直接返回源字符串。<br/>
	 * 如果expr长度为0，直接返回sourceStr。<br/>
	 * 如果expr在sourceStr中不存在，直接返回sourceStr。<br/>
	 *
	 * @param sourceStr 被截取的字符串
	 * @param expr      分隔符
	 * @return String
	 */
	public static String substringAfter(String sourceStr, String expr) {
		if (isEmpty(sourceStr) || expr == null) {
			return sourceStr;
		}
		if (expr.length() == 0) {
			return sourceStr;
		}

		int pos = sourceStr.indexOf(expr);
		if (pos == -1) {
			return sourceStr;
		}
		return sourceStr.substring(pos + expr.length());
	}

	/**
	 * 功能：检查这个字符串是不是空字符串。<br/>
	 * 如果这个字符串为null或者trim后为空字符串则返回true，否则返回false。
	 *
	 * @param chkStr 被检查的字符串
	 * @return boolean
	 */
	public static boolean isEmpty(String chkStr) {
		if (chkStr == null || chkStr == "") {
			return true;
		} else {
			return "".equals(chkStr.trim());
		}
	}

	/**
	 * 将一个字符串转化为输入流
	 *
	 * @param sInputString
	 * @return
	 */
	public InputStream getStringStream(String sInputString) {
		if (sInputString != null && !sInputString.trim().equals("")) {
			try {
				ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
				return tInputStringStream;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}
}
